package com.hl.apilibrary;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RetrofitHelper<T> {
    public void enqueue(Call<T> call, final ApiCallback<T> callback) {
        if (call == null) {
            if (callback != null) {
                callback.onFailure("");
            }
            return;
        }
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (callback != null) {
                    if (!response.isSuccessful()) {
                        callback.onFailure("");
                    } else {
                        callback.onSuccess(response.body());
                    }
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                if (callback != null) {
                    callback.onFailure(t.getMessage());
                }
            }
        });
    }

    public void execute(Call<T> call, final ApiCallback<T> callback) {
        try {
            Response<T> response = call.execute();
            if (callback != null) {
                callback.onSuccess(response.body());
            }
        } catch (IOException e) {
            if (callback != null) {
                callback.onFailure("");
            }
        }
    }
}
